import gtk
import gtk.glade
import comar
from util import UserInfo, List, GroupInfo
import veriables
from gettext import gettext as _
import gettext

gettext.bindtextdomain("user-manager", veriables.localedir)
gettext.textdomain("user-manager")
gtk.glade.bindtextdomain("user-manager", veriables.localedir)
gtk.glade.textdomain("user-manager")
gettext.install("user-manager")

class YesNoWindow:
    def __init__(self, title, message, w=350, h=80):
        yesno = gtk.glade.XML("glade/main.glade", "yesno")

        self.window = yesno.get_widget("yesno")
        self.window.resize(w,h)
        self.window.set_title(title)
        self.window.set_markup(message)

    def run(self):
        return self.window.run()


    def destroy(self):    
        self.window.destroy()

class UserEditWindow:
    def __init__(self, uid, mainwindow):
        self.wTree = gtk.glade.XML("glade/main.glade", "userEditWindow")
        self.info = UserInfo(uid)
        self.uid = uid
        self.main = mainwindow

        self.wTree.get_widget("userEditWindow").set_title(_("Edit User: %s") % self.info.name)

        self.wTree.get_widget("real_name_entry").set_text(self.info.realname)

        self.wTree.get_widget("home_label").set_text(self.info.homedir)
        self.wTree.get_widget("uid_label").set_text(uid)

        # insert text and set active user's shell
        combo = self.wTree.get_widget("shell_combo_box")
        if self.info.shell == "/bin/bash":
            combo.insert_text(0, "/bin/bash")
            combo.insert_text(1, "/bin/false")
        elif self.info.shell == "/bin/false":
            combo.insert_text(0, "/bin/false")
            combo.insert_text(1, "/bin/bash")

        combo.set_active(0)

        scroll = self.wTree.get_widget("scrolledWindow")

        self.show_system_groups = self.main.wTree.get_widget("system_users_groups").get_active()

        self.group_box = gtk.VBox()
        for group in List().getGroups():
            button = gtk.CheckButton(group[1])
            self.group_box.add(button)

            if not self.show_system_groups:
                if group[1] in self.info.groups.split(","):
                    button.set_active(True)

                # if system groups aren't selected, show only 1000+ gid
                if group[0] >= 1000 and group[0] < 6533:
                    button.show()
            else:
                if group[1] in self.info.groups.split(","):
                    button.set_active(True)

                button.show()

        scroll.add_with_viewport(self.group_box)
        self.group_box.show()
        scroll.show()

        dict = {"cancel": self.cancel,
                "apply": self.apply,
                "on_password_entry_changed": self.control_password,
                "on_password2_entry_changed": self.control_password}

        self.wTree.signal_autoconnect(dict)


    def show(self):
        self.wTree.get_widget("userEditWindow").show()

# ==============================================
#                SIGNALS
# ==============================================

    def cancel(self, widget=""):
        self.wTree.get_widget("userEditWindow").destroy()

    def control_password(self, widget):
        pass1 = self.wTree.get_widget("password_entry").get_text()
        pass2 = self.wTree.get_widget("password2_entry").get_text()
        error = self.wTree.get_widget("input_error")
        apply_button = self.wTree.get_widget("apply_button")

        if len(pass1) < 6:
            error.set_label(_("<b>Password must be \n   at least 6 char.</b>"))
            apply_button.set_sensitive(False)
        elif len(pass1) >= 6:
            if pass1 != pass2:
                error.set_label(_("<b>Password doesn't match</b>"))
                apply_button.set_sensitive(False)
            else:
                error.set_label("")
                apply_button.set_sensitive(True)
        else:
            error.set_label("")
            apply_button.set_sensitive(True)

    def apply(self, widget):
        yesno = YesNoWindow(_("Edit User"), _("Do you really want to edit this user?"))
        response = yesno.run()
        yesno.destroy()

        if response == -8:
            boxes = self.group_box.get_children()
            groups = ""

            for box in boxes:
                if box.get_active():
                    groups += "%s," % box.get_label()

            groups = groups[:-1]

            link = comar.Link()
            if len(self.wTree.get_widget("password_entry").get_text()) > 0:
                link.call("User.Manager.setUser", {"uid": self.uid, \
                          "realname": self.wTree.get_widget("real_name_entry").get_text(), \
                          "shell": self.wTree.get_widget("shell_combo_box").get_active_text(), \
                          "groups": groups, \
                          "password": self.wTree.get_widget("password_entry").get_text()})
            else:
                link.call("User.Manager.setUser", {"uid": self.uid, \
                          "realname": self.wTree.get_widget("real_name_entry").get_text(), \
                          "shell": self.wTree.get_widget("shell_combo_box").get_active_text(), \
                          "groups": groups})

            print "DEBUG [edituser]: %s" % link.read_cmd()

            self.main.appendUsers(self.show_system_groups)
            self.cancel()
            self.main.wTree.get_widget("statusbar").push(0, _('User "%s" edited.') % self.info.name)
        else:
            self.cancel()

    def test(self, widget):
        print widget

class AddUserWindow:
    def __init__(self, mainWindow):
        self.wTree = gtk.glade.XML("glade/main.glade", "addUserWindow")
        self.main = mainWindow
        print mainWindow.wTree.get_widget("addUserWindow")

        self.wTree.get_widget("home_dir_entry").set_text("/home/")
        self.wTree.get_widget("shell_combo_box").set_active(0)
        self.error(_("<b>Please specify a password</b>"))
        self.wTree.get_widget("add_button").set_sensitive(False)

        dict = {"destroy": self.destroy,
                "add_button_clicked": self.add_user,
                "control_entries": self.control_entries}

        self.wTree.signal_autoconnect(dict)


        # Add groups
        self.group_box = gtk.VBox()
        scrolledwindow = self.wTree.get_widget("scrolledwindow")

        groups = {"audio": True,
                  "dialout": False,
                  "disk": False,
                  "pnp": True,
                  "pnpadmin": False,
                  "power": False,
                  "removable": True,
                  "users": True,
                  "wheel": False}

        for group in groups:
            button1 = gtk.CheckButton(group)
            if groups[group]:
                button1.set_active(True)

            button1.show()
            self.group_box.add(button1)

        for group in List().getGroups():
            # add groups added by user
            if group[0] >= 1000 and group[0] < 6533:
                button = gtk.CheckButton(group[1])
                button.show()
                self.group_box.add(button)

        self.group_box.show()
        scrolledwindow.add_with_viewport(self.group_box)

    def destroy(self, widget=""):
        self.wTree.get_widget("addUserWindow").destroy()   

    def show(self):
        self.wTree.get_widget("addUserWindow").show()

    def error(self, text=""):
        error = self.wTree.get_widget("input_error")
        error.set_label(text)
        if len(text) > 0:
            error.show()
        else:
            error.hide()

# ==============================================
#                SIGNALS
# ==============================================

    def add_user(self, widget):
        user = self.wTree.get_widget("user_name_entry").get_text()

        yesno = YesNoWindow(_("Add User"), _('Do you really want to add user <b>%s</b>?') % user)
        response = yesno.run()
        yesno.destroy()
        # cancel
        if response == -9:
            self.destroy()
        else:
            name = self.wTree.get_widget("user_name_entry").get_text()
            realname = self.wTree.get_widget("real_name_entry").get_text()
            homedir = self.wTree.get_widget("home_dir_entry").get_text()
            shell = self.wTree.get_widget("shell_combo_box").get_active_text()
            password = self.wTree.get_widget("password_entry").get_text()
            groups = ""

            for group in self.group_box.get_children():
                if group.get_active():
                    groups += "%s," % group.get_label()

            # do not add last , char.
            groups = groups[:-1]

            link = comar.Link()
            link.call("User.Manager.addUser",
                      {"name": name,
                       "realname": realname,
                       "homedir": homedir,
                       "shell": shell,
                       "password": password,
                       "groups": groups})

            print "DEBUG [adduser]: %s" % link.read_cmd()

            self.main.appendUsers(self.main.wTree.get_widget("system_users_groups").get_active())
            self.main.wTree.get_widget("statusbar").push(0, _('User "%s" added') % name)
            self.destroy()

    def control_entries(self, widget):
        pass1 = self.wTree.get_widget("password_entry").get_text()
        pass2 = self.wTree.get_widget("password2_entry").get_text()
        username = self.wTree.get_widget("user_name_entry").get_text()
        realname = self.wTree.get_widget("real_name_entry").get_text()
        homedir = self.wTree.get_widget("home_dir_entry").get_text()

        self.wTree.get_widget("home_dir_entry").set_text("/home/" + username)

        add_button = self.wTree.get_widget("add_button")

        control_passwd = False
        control_username = False
        control_realname = False
        control_user_password = False

        if len(pass1) < 6:
            self.error(_("<b>Password must be \n   at least 6 char.</b>"))
        elif len(pass1) >= 6:
            if pass1 != pass2:
                self.error(_("<b>Password doesn't match</b>"))
            else:
                self.error()
                control_passwd = True

        if len(username) and len(realname) > 0:
            if username == pass1 or realname == pass1:
                self.error(_("<b>Don't use your name as a password</b>"))
            else:
                control_user_password = True

        if len(username) > 0:
            control_username = True

        if len(realname) > 0:
            control_realname = True

        if control_passwd and control_username and control_realname and control_user_password is True:
            add_button.set_sensitive(True)
        else:
            add_button.set_sensitive(False)

class AddGroupWindow:
    def __init__(self, mainWindow):
        self.wTree = gtk.glade.XML("glade/main.glade", "addGroupWindow")
        self.main = mainWindow

        dict = {"destroy": self.destroy,
                "on_toolbutton_ok_clicked": self.add_group,
                "on_entry_group_name_changed": self.control_entry}

        self.wTree.get_widget("toolbutton_ok").set_sensitive(False)

        self.wTree.signal_autoconnect(dict)

    def destroy(self, widget=""):
        self.wTree.get_widget("addGroupWindow").destroy()

    def show(self, widget=""):
        self.wTree.get_widget("addGroupWindow").show()

# ==============================================
#                SIGNALS
# ==============================================

    def control_entry(self, widget):
        control_groupname = False

        if len(widget.get_text()) > 0:
            control_groupname = True
        else:
            control_groupname = False

        self.wTree.get_widget("toolbutton_ok").set_sensitive(control_groupname)

    def add_group(self, widget):
        groupname = self.wTree.get_widget("entry_group_name").get_text()

        yesno = YesNoWindow(_("Add Group"), _("Do you really want to add group <b>%s</b>?") % groupname)
        response = yesno.run()
        yesno.destroy()

        if response == -8:
            link = comar.Link()
            link.call("User.Manager.addGroup", {"gid": "auto", "name": groupname})

            print "DEBUG [addgroup]: %s" % link.read_cmd()

            self.main.appendGroups(self.main.wTree.get_widget("system_users_groups").get_active())
            self.main.wTree.get_widget("statusbar").push(0, _('Group "%s" added') % groupname)
            self.destroy()
        else:
            self.destroy()
